// pages/student/join-class/index.js
import { Serve } from '../../../utils/index'
Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		name: '',
		course: '',
		host: '',
    classes: [],
    visible: false,
    code: '',
    currentCode: '',
    currentClass: ''
	},

	handleNameInput(e) {
		this.setData({ name: e.detail.value })
	},

	handleCourseInput(e) {
		this.setData({ course: e.detail.value })
	},

	handleHostInput(e) {
		this.setData({ host: e.detail.value })
	},

  handleCodeInput(e) {
    this.setData({ code: e.detail.value.toUpperCase() })
  },

  async searchClasses() {
    const openid = wx.getStorageSync('openid')
    const { host, name, course } = this.data
    if (!host && !name && !course) {
      wx.showToast({
        title: '您至少要填写一项字段',
        icon: 'none',
        mask: true
      })
      return 0
    }
    wx.showLoading({
      title: '查询中',
      mask: true
    })
    let classes = await Serve.GetClass({ host, name, course })
    classes = classes.map(item => {
      let join = false
      if (item.members.find(i => i.openid === openid )) {
        join = true
      }
      return { ...item, join }
    })
    this.setData({ classes })
    wx.hideLoading()
  },

  showCodePanel(e) {
    const { code, id } = e.currentTarget.dataset
    this.setData({ visible: true, currentCode: code, currentClass: id })
  },

  hideCodePanel() {
    this.setData({ visible: false, currentCode: '', currentClass: '', code: '' })
  },

  async joinClass() {
    const { currentClass, currentCode, code } = this.data
    if (currentCode !== code) {
      wx.showToast({ title: '班级码错误', mask: true, icon: 'error' })
      return 0
    }
    wx.showLoading({ title: '加入班级', mask: true })
    const result = await Serve.AddStudent(currentClass)
    wx.hideLoading()
    this.hideCodePanel()
    wx.navigateBack()
  },

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad(options) {},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady() {},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow() {
  },

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide() {},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload() {},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh() {},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom() {},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage() {},
})
